package com.jmu.posms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jmu.posms.common.Result;
import com.jmu.posms.dto.NewspaperInputDto;
import com.jmu.posms.exception.ServiceException;
import com.jmu.posms.pojo.Newspaper;
import com.jmu.posms.service.NewspaperService;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/news")
public class NewsPaperController {
    @Resource
    NewspaperService newspaperService;

    @GetMapping("/get/page")
    public Result page(Integer page,Integer pageSize,String name){
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Newspaper> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件  like ---> %name%
        queryWrapper.like(StringUtils.isNotEmpty(name),Newspaper::getName,name);

        //执行查询
        try{
            newspaperService.page(pageInfo, queryWrapper);
        }catch (Exception e){
            throw new ServiceException("600","分页查询失败");
        }
        return Result.success(pageInfo,"查询成功");
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody NewspaperInputDto inputDto){
        Newspaper newspaper = new Newspaper();
        BeanUtils.copyProperties(inputDto,newspaper);

        //通过UUID生成id
        newspaper.setId(UUID.randomUUID().toString());
        try{
            newspaperService.save(newspaper);
        }catch (Exception e){
            throw new ServiceException("600","插入失败");
        }

        return Result.success(null,"插入成功");
    }

    @PutMapping("/update")
    public Result update(@RequestBody Newspaper newspaper){
        try{
            newspaperService.updateById(newspaper);
        }catch (Exception e){
            throw new ServiceException("600","修改失败");
        }
        return Result.success(null,"修改成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable String id){
        try{
            newspaperService.removeById(id);
        }catch (Exception e){
            throw new ServiceException("600","删除失败");
        }
        return Result.success(null,"删除成功");
    }

    @DeleteMapping("/delete")
    public Result deleteAll(@RequestBody List<String> ids){
//        System.out.println(ids);
        try{
            newspaperService.removeBatchByIds(ids);
        }catch (Exception e){
            throw new ServiceException("600","批量删除失败");
        }
        return Result.success(null,"批量删除成功");
    }
}
